import java.util.ArrayList;
import java.io.*;

import javax.swing.tree.DefaultMutableTreeNode;

/**
 * EBook Organizer
 * 5/26/2010
 * <P>
 * A class that contains information of a folder which contains other folders
 * and Ebooks
 * </P>
 * @version 0.2
 */
public class Folder extends DefaultMutableTreeNode implements java.io.Serializable {
	/**
	 * 
	 */
	private static final long serialVersionUID = 501092678715134606L;
	
	private ArrayList<Folder> folders;
	private ArrayList<EBook> books;

	File dir;
	
	private OrganizerModel model;
	
	public Folder(File file, OrganizerModel model) {
		super();
		dir = file;
		folders = new ArrayList<Folder>();
		books = new ArrayList<EBook>();
		
		this.model = model;
		
		this.setAllowsChildren( true );
		
		//Search the folder for other folders or files:
		initialize();
		
	}
	
	
	private void initialize () {
		// get all the files and directories
		File [] children = dir.listFiles();
		// loop over the file/directory listing
		for(File file : children) {
		 // is the current item a file?
		if(file.isFile()) { // process as file
			FileType type = model.getSettingsModel().isOfType(file);
			
			if ( type!=null ) {
				books.add( new EBook(file, type) );
			}
				
		} 
		else { // dir.isDirectory()
//			folders.add( new Folder(file) );
		}}
	}
	
	public void addFolder(Folder folder) {
		folders.add(folder);
	}
	
	public Folder getFolder( int index ) {
		return folders.get(index);
	}
	
	public int getNumberOfFolders() {
		return folders.size();
	}
	
	public void addBook(EBook book) {
		books.add(book);
	}
	
	public EBook getBook( int index) {
		return books.get(index);
	}
	
	public int getNumberOfBooks() {
		return books.size();
	}
	
	public String display() {
		String buff = this.toString()+"\n";
		
		buff+="\t\tFolders: \n";
		for (int i =0; i <folders.size(); i++) { //add folders
			buff+="\t\t"+folders.get(i).display()+"\n";
		}
		buff+="\t\tBooks: \n";
		for (int i =0; i <books.size(); i++) { //add books
			buff+="\t\t"+books.get(i)+"\n";
		}
		
		return buff;
	}
	
	public String toString() {
		return dir.getPath();
	}
}
